package com.generate.tools.utils;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public final class PropertiesUtil {

    public static final String SUFFIX = ".properties";

    public static String getName(final String name) {
        String tempName = name;
        if (tempName.lastIndexOf(SUFFIX) <= -1) {
            tempName = tempName + getSystemName() + SUFFIX;
        }
        return tempName;
    }

    private static String getSystemName() {
        String system = System.getProperty("os.name").toLowerCase();
        if (system == null || system == "") {
            return "";
        }
        if (system.startsWith("window")) {
            return "-window";
        } else if (system.startsWith("linux")) {
            return "-linux";
        }
        return system;

    }

    public static boolean readBoolean(String key, String name) {
        return Boolean.parseBoolean(read(key, name));
    }

    public static int readInt(String key, String name) {
        return Integer.parseInt(read(key, name));
    }

    public static String read(String key, String name) {
        Properties prop = readConfigFile(name);
        if (prop.containsKey(key)) {
            return prop.getProperty(key);
        }
        return "";
    }

    public synchronized static Properties readConfigFile(final String name) {
        InputStream in = null;
        Properties prop = null;
        try {
            prop = new Properties();
            in = PropertiesUtil.class.getClassLoader()
                .getResourceAsStream(getName(name));
            if (in != null) {
                prop.load(in);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return prop;
    }
}
